import { config } from "../config/index";
import multer from 'koa-multer';
import path from "path";

export class utils {
    /**
     * 统一设置网站浏览器的 title 标题内容
     * @param title 
     */
     public static titleName(title:string):string {
        return `${title}${config.title}`
    }

  static  fileUploadOptions =  {
      storage: multer.diskStorage({
          destination: (req: any, file: any, cb: any) => { 
            cb(null, path.join(config.initPlugins.staticPath,'/img/dynamic'));
          },
          filename: (req: any, file: any, cb: any) => { 
            cb(null, Date.now()+'_'+`${Math.floor(Math.random()*10)}`+'.'+(file.originalname).split('.')[(file.originalname).split('.').length-1]);
          }
      }),
      limits: {
          fieldNameSize: 1024 * 1024 / 2,
          fileSize: 1024 * 1024 * 20
      }

  }
  //转换表情
  static utf16toEntities(str:string) { 
    let patt=/[\ud800-\udbff][\udc00-\udfff]/g; // 检测utf16字符正则 
    str = str.replace(patt, function(char:string){ 
      let H, L, code; 
            if (char.length===2) { 
                H = char.charCodeAt(0); // 取出高位 
                L = char.charCodeAt(1); // 取出低位 
                code = (H - 0xD800) * 0x400 + 0x10000 + L - 0xDC00; // 转换算法 
                return "&#" + code + ";"; 
            } else { 
                return char; 
            } 
        }); 
    return str; 
}

//转成表情
static uncodeUtf16(str:string){
  var reg = /\&#.*?;/g;
  var result = str.replace(reg,function(char:any){
      var H,L,code;
      if(char.length == 9 ){
          code = parseInt(char.match(/[0-9]+/g));
          H = Math.floor((code-0x10000) / 0x400)+0xD800;
          L = (code - 0x10000) % 0x400 + 0xDC00;
          return unescape("%u"+H.toString(16)+"%u"+L.toString(16));
      }else{
          return char;
      }
  });
  return result;
}
 
}
